﻿using System;
using System.Configuration;
using System.Reflection;
using System.Web.Configuration;
using System.Xml;

using umbraco.cms.businesslogic.packager.standardPackageActions;
using umbraco.interfaces;

namespace Our.Umbraco.Tree.Elmah.Packager.Actions
{
	public class AddConfigurationSectionGroup : IPackageAction
	{
		public string Alias()
		{
			return "AddConfigurationSectionGroup";
		}

		public bool Execute(string packageName, XmlNode xmlData)
		{
			throw new NotImplementedException();
		}

		public XmlNode SampleXml()
		{
			var sample = @"
<Action runat=""install"" undo=""true"" alias=""AddConfigurationSectionGroup"">
	<sectionGroup name=""elmah"">
		<section name=""errorLog"" requirePermission=""false"" type=""Elmah.ErrorLogSectionHandler, Elmah"" />
	</sectionGroup>
</Action>";
			return helper.parseStringToXmlNode(sample);
		}

		public bool Undo(string packageName, XmlNode xmlData)
		{
			try
			{
				var config = WebConfigurationManager.OpenWebConfiguration("~");
				var sectionName = xmlData.SelectSingleNode("//SectionGroup").Attributes["name"].Value;

				if (config.Sections[sectionName] != null)
				{
					config.Sections.Remove(sectionName);
					config.Save(ConfigurationSaveMode.Full);
				}

				return true;
			}
			catch
			{
				return false;
			}
		}
	}
}
